package org.ueg.pdv.converters;

import java.util.Map;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

import org.ueg.pdv.model.Cliente;


@FacesConverter(value="clienteConverter", forClass=Cliente.class)
public class ClienteConverter implements Converter {

	@Override
	public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) {
		if (arg2 != null)
			return this.getAttributesFrom(arg1).get(arg2);
		return null;
	}

	@Override
	public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2) {
		// TODO Auto-generated method stub
		if (arg2 != null && !"".equals(arg2)){
			Cliente cliente = (Cliente) arg2;
			if (cliente.getId() != null){
				this.addAtribute(arg1, cliente);
				
				if (cliente.getId() != null)
					return String.valueOf(cliente.getId());
				return (String) arg2;
			}
		}
		return "";
	}
	
	private void addAtribute(UIComponent component, Cliente cliente){
		this.getAttributesFrom(component).put(cliente.getId().toString(), cliente);
	}
	
	private Map<String, Object> getAttributesFrom(UIComponent component){
		return component.getAttributes();
	}
}